//
//  ViewController.m
//  19---JSON
//
//  Created by 冀永金 on 16/8/9.
//  Copyright © 2016年 冀永金. All rights reserved.
//

#import "ViewController.h"
#import "MyCollectionViewLayout.h"
#import "TitleCollectionViewCell.h"
#import "ContentTitle.h"
@interface ViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,MyCollectionViewLayoutDelegate>
//@property (weak, nonatomic) IBOutlet UICollectionView *collection;
@property (weak, nonatomic) IBOutlet UICollectionView *collection;
@property (nonatomic, strong) NSMutableArray<ContentTitle *> *titleMarr;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    MyCollectionViewLayout *laout = (MyCollectionViewLayout *)self.collection.collectionViewLayout;
    laout.delegate = self;
    [self handleData];
    // Do any additional setup after loading the view, typically from a nib.
}
- (void)handleData {
    // JSON  解析
    // 通过一个Data,将JSON格式转换成OC认识的内容
    // 数组、字典
    self.titleMarr = [NSMutableArray array];
    NSString *dataPath = [[NSBundle mainBundle]pathForResource:@"FirstJSON" ofType:@"json"];
    NSData *data = [NSData dataWithContentsOfFile:dataPath];
    NSError *error = nil;
    NSDictionary *jsonDic  =  [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
    NSDictionary *dic = jsonDic[@"tabs"];
    NSArray *list = dic[@"list"];
    for (NSDictionary *dic in list) {
        ContentTitle *title = [ContentTitle contentWithDic:dic];
        [self.titleMarr addObject:title];
    }
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.titleMarr.count;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
   TitleCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"pool" forIndexPath:indexPath];
    ContentTitle *content = self.titleMarr[indexPath.row];
    [cell setContent:content];
    return cell;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout
 heightForItemAtIndexPath:(NSIndexPath *)indexPath {
    ContentTitle *content = _titleMarr[indexPath.row];
   CGRect newRect =  [content.title boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, self.collection.bounds.size.height) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17]} context:nil];
    
    return newRect.size.width + 1;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
